package top.yifengxiner.framework.shiro.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import top.yifengxiner.common.core.pojo.entity.SysUser;
import top.yifengxiner.common.exception.user.UserException;
import top.yifengxiner.framework.shiro.service.SysLoginService;

import java.util.HashSet;
import java.util.Set;

/**
 * @author ：baixiao
 * @date ：Created in 2021/5/4 18:37
 * @description：自定义realm
 * @modified By：
 * @version: 0.0.1$
 */
public class UserRealm extends AuthorizingRealm
{

    @Autowired
    private SysLoginService loginService;

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals)
    {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }

    /**
     * 登录验证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException
    {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        String password = "";

        if(upToken.getPassword() != null)
        {
            password = new String(upToken.getPassword());
        }
        SysUser user = null;
        try
        {
            user = loginService.getUser(username,password);
        }
        catch (UserException e)
        {
            throw new UnknownAccountException(e.getMessage(),e);
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,password,getName());
        return info;
    }
}
